"""Activation and license check routes."""
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from .. import schemas, crud, utils, models
from ..deps import get_db

router = APIRouter(prefix="/activate", tags=["Activation"])

def _build_response(lic: models.License, device_hash: str):
    # Ensure all timestamps are sent in the standard ISO 8601 format with 'Z' for UTC.
    # This provides a consistent, unambiguous format for the client to parse.
    # Ensure expires_at is timezone-aware. If it's naive, assume UTC and update DB for good.
    expires_dt = lic.expires_at
    if expires_dt and expires_dt.tzinfo is None:
        expires_dt = expires_dt.replace(tzinfo=timezone.utc)
        lic.expires_at = expires_dt  # persist the fix so future requests are correct
    expires_at_str = expires_dt.isoformat().replace('+00:00', 'Z') if expires_dt else None
    last_verified_at_str = datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')

    payload = {
        "device_hash": device_hash,
        "expires_at": expires_at_str,
        "last_verified_at": last_verified_at_str,
        "offline_grace_days": 30,
    }
    signature = utils.sign_payload(payload)
    return {"status": "success", "license_data": payload, "signature": signature}


@router.post("", response_model=schemas.ActivateResp)
async def activate(req: schemas.ActivateReq, db: AsyncSession = Depends(get_db)):
    code = await crud.get_activation_code_for_update(db, req.activation_code)
    if not code or not code.enabled:
        raise HTTPException(400, "激活码无效或已被禁用")

    lic = await crud.get_license(db, code.id, req.device_hash)
    if not lic:
        license_count = await crud.get_license_count(db, code.id)
        if license_count >= code.quota:
            raise HTTPException(400, "激活码已超出绑定数量")
        expires_at = (
            datetime.now(timezone.utc) + timedelta(days=code.duration_days)
            if code.duration_days is not None
            else None
        )
        lic = await crud.create_license(db, code.id, req.device_hash, expires_at)
    
    return _build_response(lic, req.device_hash)


@router.post("/check", response_model=schemas.ActivateResp)
async def check(req: schemas.ActivateReq, db: AsyncSession = Depends(get_db)):
    lic = await crud.get_license_by_code_and_device(db, req.activation_code, req.device_hash)
    if not lic or not lic.activation_code.enabled:
        raise HTTPException(403, "授权无效或已被禁用")
    if lic.expires_at and lic.expires_at < datetime.now(timezone.utc):
        raise HTTPException(403, "授权已过期")
    return _build_response(lic, req.device_hash)
